﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

namespace DARE.Save.DataStructures
{
    public class CTerrainData : ISaveData
    {
        public string heightmap;
        public string heightmapTexture;
        public float bump;
        public float scale;
        public int subSizeX;
        public int subSizeY;
        public string name;
        public bool isPhysicalized;

        public void FillDataStructure(object terrain)
        {
            CTerrainInfo terrainInfo = terrain as CTerrainInfo;
            if (terrainInfo == null)
                return;
            name = terrainInfo.OwnerNode.Name;
            heightmap = DARE.CResourceMgr.GetResourceName(terrainInfo.Heightmap);
            if (terrainInfo.OwnerNode.Children.Count > 0 && (terrainInfo.OwnerNode.Children.First().Value.Entity.Model is CSubTerrainModel))
            {
                CSubTerrainModel stm = (terrainInfo.OwnerNode.Children.First().Value.Entity.Model as CSubTerrainModel);
                heightmapTexture = DARE.CResourceMgr.GetResourceName(stm.Effect.ColorMap);
                subSizeX = stm.TerrainModel.SubSizeX;
                subSizeY = stm.TerrainModel.SubSizeZ;
                if (stm.Entity.Physic != null)
                    isPhysicalized = true;
            }
            bump = terrainInfo.Bump;
            scale = terrainInfo.Scale;
        }

        public void FillFromDataStructure(out object terrainNode, params object[] paramsData)
        {
            DARE.CTerrainInfo terrainInfo = new DARE.CTerrainInfo(
                DARE.CResourceMgr.Load<Texture2D>(heightmap), bump, scale);
            DARE.CTerrainModel terrainModel = new DARE.CTerrainModel(terrainInfo, subSizeX, subSizeY);

            if (heightmapTexture != null)
                terrainModel.SetTexture(DARE.CResourceMgr.Load<Texture2D>(heightmapTexture));

            terrainNode = terrainModel.RootNode.SetName(name);

            if (isPhysicalized)
            {
                (terrainNode as CNode).Entity.CreatePhysicTerrain(terrainInfo);
                (terrainNode as CNode).Entity.Physic.CollisionType = DARE.APhysicObject.ECollisionType.GROUND;
            }
        }
    }
}
